﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Gman.WebApp.ServiceControllers;
using Gman.Entity.Entities;
using System.Web.Caching;
using System.Web.UI;
using Gman.WebApp.Controllers.Base;
using Gman.WebApp.Models;
using Gman.WebApp.Models.Validator;

namespace Gman.WebApp.Controllers
{
    public class DiagnosticoController : BaseController
    {

        private GestionServiceController service = new GestionServiceController();
        private OperacionServiceController operacion = new OperacionServiceController();

        public ActionResult Search()
        {
            var cache = new CacheProvider();
            DiagnosticoBE diagnostico = new DiagnosticoBE();

            var model = new DiagnosticoModel(diagnostico);
            cache.Set(model.ID.Value.ToString(), model);

            model.Action = "search";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Diagnostico/Edit.aspx", model);

        }

        public ActionResult Create()
        {
            var cache = new CacheProvider();
            DiagnosticoBE diagnostico = new DiagnosticoBE();

            var model = new DiagnosticoModel(diagnostico);
            cache.Set(model.ID.Value.ToString(), model);
            model.Action = "create";
            model.ToolBar = new ToolBarModel();

            return View(@"~/Views/Diagnostico/Edit.aspx", model);
        }


        public DiagnosticoModel GetDiagnosticoModel(Guid id)
        {
            var cache = new CacheProvider();

            string key = id.ToString();
            var existingModel = cache.Get(key);
            if (existingModel == null)
            {
                existingModel = new DiagnosticoModel(new DiagnosticoBE());
                cache.Set(key, existingModel);
            }
            return (DiagnosticoModel)existingModel;
        }

        public ActionResult UpdateField(string fieldName, string fieldValue, Guid id, string setterFormatOptions)
        {
            DiagnosticoModel model = GetDiagnosticoModel(id);
            SetterFormatOptions setterFormatOptionsEnum = SetterFormatOptionsHelper.Parse(setterFormatOptions);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();

            var setter = new PropertySetter<DiagnosticoModel>.SetterOptions();
            setter.objectToSet = model;
            setter.property = fieldName;
            setter.val = fieldValue;
            setter.SetterFormatOptions = setterFormatOptionsEnum;
            setter.validationList = validationList;

            object valueWasSet = PropertySetter<DiagnosticoModel>.SetFinalObject(setter);


            validationList.AddRange(new DiagnosticoModelValidator().Validate(model));

            return Json
                (new
                {
                    result = true,
                    PropertyValidationList = validationList,
                }
                );
        }

        public ActionResult GetValidation(Guid id)
        {
            DiagnosticoModel model = GetDiagnosticoModel(id);
            List<KeyValuePair<string, string>> validationList = new List<KeyValuePair<string, string>>();
            List<KeyValuePair<string, string>> propertyChangeList = new List<KeyValuePair<string, string>>();

            validationList.AddRange(new DiagnosticoModelValidator().Validate(model));

            return Json(new
            {
                PropertyValidationList = validationList,
                PropertyVisibilityList = propertyChangeList
            });
        }

        public ViewResult LoadAddOrEditActivos(Guid id, Guid? activoGuid)
        {
            var cache = new CacheProvider();
            DiagnosticoDetalleModel activo = null;
            if (!activoGuid.HasValue)
            {
                activo = new DiagnosticoDetalleModel(new DiagnosticoDetalleBE());
                activo.Action = "create";
                cache.Set(activo.ID.Value.ToString(), activo);
            }
            else
            {
                var activoModel = GetDiagnosticoModel(id);
                activo = activoModel.DiagnosticoDetalles.FirstOrDefault(x => x.ID == activoGuid.Value);
                activo.Action = "edit";
                if (activo.DiagnosticoDetalle.IDDiagnostico.HasValue)
                {
                    cache.Set(activoGuid.ToString(), activo);
                }
            }
            return View(@"~/Views/DiagnosticoDetalle/AddOrEditDetalleDiag.ascx", activo);
        }


        public JsonResult AddOrEditActivo(Guid id, Guid activoGuid, string action)
        {
            try
            {
                var activo = new DiagnosticoDetalleController().GetDiagnosticoDetalleModel(activoGuid);
                var model = GetDiagnosticoModel(id);
                bool estado = true;
                if (action == "create")
                {
                    if (model.DiagnosticoDetalles.Count >= 1)
                    {


                        foreach (var existe in model.DiagnosticoDetalles)
                        {
                            if (activo.BajaActivoDetalle.Bien.IDBien == existe.Bien.IDBien)
                            {
                                estado = false;
                            }

                            if (activo.BajaActivoDetalle.Bien.IDBien == existe.BajaActivoDetalle.Bien.IDBien)
                            {
                                estado = false;
                            }

                        }

                        if (estado)
                        {
                            activo.DiagnosticoDetalle.IDDiagnostico= 0;
                            model.DiagnosticoDetalles.Add(activo);
                        }

                    }
                    else
                    {
                        activo.DiagnosticoDetalle.IDDiagnostico = 0;
                        model.DiagnosticoDetalles.Add(activo);
                    }

                }

                else if (action == "edit")
                {
                    var activoToEdit = model.DiagnosticoDetalles.FirstOrDefault(x => x.ID == activoGuid);
                    activoToEdit = activo;
                }

                return AjaxResultSuccessNoParam();
            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }

        public ViewResult GetListaActivo(Guid id)
        {
            DiagnosticoModel model = GetDiagnosticoModel(id);
            return View(@"~/Views/Diagnostico/ListaDiagnosticoDetalle.ascx", model);
        }

        public ViewResult DeleteActivo(Guid id, Guid activoGuid)
        {
            var model = GetDiagnosticoModel(id);
            var activo = model.DiagnosticoDetalles.FirstOrDefault(x => x.ID == activoGuid);

            model.DiagnosticoDetalles.Remove(activo);

            if (model.Action == "edit" && activo.DiagnosticoDetalle.IDDiagnostico > 0)
            {
                model.toDelete.Add(activo);
            }

            return View(@"~/Views/Diagnostico/ListaDiagnosticoDetalle.ascx", model);
        }


        public JsonResult Save(Guid id, string action)
        {
            try
            {
                UsuariosBE user = (UsuariosBE)Session["user"];
                DiagnosticoModel model = GetDiagnosticoModel(id);
                DiagnosticoBE obj = new DiagnosticoBE();

                List<DiagnosticoDetalleBE> ListDiagnosticos = new List<DiagnosticoDetalleBE>();
                foreach (var diagnosticos in model.DiagnosticoDetalles)
                {
                    diagnosticos.DiagnosticoDetalle.IDBien = diagnosticos.BajaActivoDetalle.Bien.IDBien;
                    ListDiagnosticos.Add(diagnosticos.DiagnosticoDetalle);
                }

                List<DiagnosticoDetalleBE> Listeliminados = new List<DiagnosticoDetalleBE>();
                foreach (var eliminados in model.toDelete)
                {
                    Listeliminados.Add(eliminados.DiagnosticoDetalle);
                }


                if (model.Action == "create")
                {

                    DiagnosticoBE diagnostico = new DiagnosticoBE();
                    diagnostico = model.Diagnostico;
                    diagnostico.CodDiag = "DG" + (service.ListarDiagnostico(obj).Count + 1);
                    diagnostico.UsuReg = user.NomUsu;
                    diagnostico.TermCnxReg = Environment.MachineName;
                    diagnostico.IDEmp = user.IDEmp;

                    int codDiag = service.RegistrarDiagnostico(diagnostico, ListDiagnosticos);

                    if (codDiag >= 1)
                    {
                        //TempData["IDDiagnostico"] = codDiag;
                        return AjaxResultSuccess(string.Format("Diagnostico de Activo {0} se guardo exitosamente.", diagnostico.CodDiag));
                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }

                }
                if (model.Action == "edit")
                {
                    DiagnosticoBE diagnostico = new DiagnosticoBE();
                    diagnostico = model.Diagnostico;
                    diagnostico.TermCnxMod = Environment.MachineName;
                    diagnostico.UsuMod = user.NomUsu;

                    int codDiag = service.ActualizarDiagnostico(diagnostico, ListDiagnosticos, Listeliminados);

                    if (codDiag >= 1)
                    {
                        //TempData["IDDiagnostico"] = codDiag;
                        return AjaxResultSuccess(string.Format("Diagnostico {0} se actualizo exitosamente.", diagnostico.CodDiag));

                    }
                    else
                    {
                        return AjaxResultSuccess(string.Format("No se guardo exitosamente."));
                    }
                }



                return AjaxResultSuccessNoParam();

            }
            catch (Exception ex)
            {
                return AjaxResultError(ex.Message);
            }
        }


        public ActionResult DoSearch(string cod)
        {
            var cache = new CacheProvider();

            DiagnosticoBE obj = new DiagnosticoBE();
            obj.CodDiag = cod;

            var diagnostico = service.ObtenerDiagnostico(obj);
            if (diagnostico != null)
            {
                var model = new DiagnosticoModel(diagnostico);
                cache.Set(model.ID.Value.ToString(), model);
                model.Action = "query";
                model.ToolBar = new ToolBarModel();

                Int64 IDDiagnostico = Convert.ToInt64(model.Diagnostico.IDDiagnostico);
                TempData["IDDiagnostico"] = IDDiagnostico;

                model.DiagnosticoDetalles = new List<DiagnosticoDetalleModel>();

                IList<DiagnosticoDetalleBE> listaDiagnosticoDetalles = new List<DiagnosticoDetalleBE>();
                DiagnosticoDetalleBE diagnosticoDetalle = new DiagnosticoDetalleBE();
                diagnosticoDetalle.IDDiagnostico = Convert.ToInt64(TempData["IDDiagnostico"]);
                listaDiagnosticoDetalles = service.ListarDiagnosticoDetalle(diagnosticoDetalle);

                foreach (DiagnosticoDetalleBE diagnosticos in listaDiagnosticoDetalles)
                {

                    IList<BienBE> listaBienes = new List<BienBE>();
                    BienBE bien = new BienBE();
                    bien.IDEmp = 1;
                    listaBienes = operacion.ListarBien(bien);

                    foreach (BienBE bienes in listaBienes)
                    {
                        if (bienes.IDBien == diagnosticos.IDBien)
                        {
                            model.DiagnosticoDetalles.Add(new DiagnosticoDetalleModel(bienes, diagnosticos));
                        }
                    }


                }

                return View(@"~/Views/Diagnostico/Edit.aspx", model);
            }

            return AjaxResultSuccess(string.Format("No se encontró baja de activo :{0} ", cod));
        }



        public ActionResult Edit(string cod)
        {
            var cache = new CacheProvider();

            DiagnosticoBE obj = new DiagnosticoBE();
            obj.CodDiag = cod;

            var diagnostico = service.ObtenerDiagnostico(obj);
            if (diagnostico != null)
            {
                var model = new DiagnosticoModel(diagnostico);
                cache.Set(model.ID.Value.ToString(), model);
                model.Action = "edit";
                model.ToolBar = new ToolBarModel();

                Int64 IDDiagnostico = Convert.ToInt64(model.Diagnostico.IDDiagnostico);
                TempData["IDDiagnostico"] = IDDiagnostico;

                model.DiagnosticoDetalles = new List<DiagnosticoDetalleModel>();

                IList<DiagnosticoDetalleBE> listaDiagnosticoDetalles = new List<DiagnosticoDetalleBE>();
                DiagnosticoDetalleBE diagnosticoDetalle = new DiagnosticoDetalleBE();
                diagnosticoDetalle.IDDiagnostico = Convert.ToInt64(TempData["IDDiagnostico"]);
                listaDiagnosticoDetalles = service.ListarDiagnosticoDetalle(diagnosticoDetalle);

                foreach (DiagnosticoDetalleBE diagnosticos in listaDiagnosticoDetalles)
                {

                    IList<BienBE> listaBienes = new List<BienBE>();
                    BienBE bien = new BienBE();
                    bien.IDEmp = 1;
                    listaBienes = operacion.ListarBien(bien);

                    foreach (BienBE bienes in listaBienes)
                    {
                        if (bienes.IDBien == diagnosticos.IDBien)
                        {
                            model.DiagnosticoDetalles.Add(new DiagnosticoDetalleModel(bienes, diagnosticos));
                        }
                    }


                }

                return View(@"~/Views/Diagnostico/Edit.aspx", model);
            }

            return AjaxResultSuccess(string.Format("No se encontró baja de activo :{0} ", cod));
        }

    }
}
